package com.stylefeng.guns.rest.modular.order;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.plugins.Page;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.stylefeng.guns.api.alipay.AliPayServiceAPI;
import com.stylefeng.guns.api.alipay.vo.AliPayInfoVO;
import com.stylefeng.guns.api.alipay.vo.AliPayResultVO;
import com.stylefeng.guns.api.order.service.OrderServiceAPI;
import com.stylefeng.guns.api.order.vo.OrderVO;
import com.stylefeng.guns.core.util.TokenBuckt;
import com.stylefeng.guns.rest.common.CurrentUser;
import com.stylefeng.guns.rest.modular.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @创建人 lIUJF
 * @创建时间 2019/1/11
 * @描述:
 */
@Slf4j
@RestController
@RequestMapping("/order/")
public class OrderController {
	private static TokenBuckt tokenBuckt = new TokenBuckt();
	private static final String  IMG_PRE = "";


	@Reference(interfaceClass = OrderServiceAPI.class, check = false, group = "order2018")
	private OrderServiceAPI orderServiceAPI;

	@Reference(interfaceClass = OrderServiceAPI.class, check = false, group = "order2017")
	private OrderServiceAPI orderServiceAPI2017;

	@Reference(interfaceClass = AliPayServiceAPI.class,check = false)
	private AliPayServiceAPI aliPayServiceAPI;

	//服务降级，退而求其次，给一个降级的返回
	public ResponseVO error(Integer field, String solaSeats, String seatName){
		return ResponseVO.serviceFail("抱歉，下单人过多，请稍后重试");
	}

	// 购票
	/*
        信号量隔离
        线程池隔离
        线程切换
        fallbackMethod 核心方法，注解方法。
        requestVolumeThreshold：请求数量,熔断器开关开启
        errorThresholdPercentage：error数量
     */
	@HystrixCommand(fallbackMethod = "error", commandProperties = {@HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),//threadLoal
			@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "4000"),//4秒超时异常
			@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50")}, threadPoolProperties = {@HystrixProperty(name = "coreSize", value = "1"), @HystrixProperty(name = "maxQueueSize", value = "10"), @HystrixProperty(name = "keepAliveTimeMinutes", value = "1000"), @HystrixProperty(name = "queueSizeRejectionThreshold", value = "8"), @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "12"), @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "1500")})
	//购票  验证用户登录，token. 应为post请求
	@RequestMapping(value = "buyTickets", method = RequestMethod.POST)
	public ResponseVO buyTickets(Integer fieldId, String soldSeats, String seatsName){
		try {
			if (tokenBuckt.getToken()) {
				//验证售出的票是否为真
				boolean trueSeats = orderServiceAPI.isTrueSeats(fieldId + "", soldSeats);
				boolean notSoldSeats = orderServiceAPI.isNotSoldSeats(fieldId + "", soldSeats);
				if (trueSeats && notSoldSeats) {
					//已经销售的座位里，有没有这些座位
					//创建订单信息
					String currentUserId = CurrentUser.getCurrentUser();
					if (StringUtils.isNotBlank(currentUserId)) {
						OrderVO orderVO = orderServiceAPI.saveOrderInfo(fieldId, soldSeats, seatsName, Integer.valueOf(currentUserId));
						if (null != orderVO) {
							return ResponseVO.success(orderVO);
						} else {
							log.error("购票未成功");
							return ResponseVO.serviceFail("购票业务异常");
						}
					} else {
						return ResponseVO.serviceFail("用户未登陆");
					}
				} else {
					return ResponseVO.serviceFail("该座位暂不可选择");
				}

			} else {
				return ResponseVO.serviceFail("购票业务繁忙,稍后重试");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("购票业务异常", e);
			return ResponseVO.serviceFail("购票业务异常");
		}
	}


	@RequestMapping(value = "getOrderInfo", method = RequestMethod.POST)
	public ResponseVO getOrderInfo(@RequestParam(name = "nowPage", required = false, defaultValue = "1") Integer nowPage, @RequestParam(name = "pageSize", required = false, defaultValue = "5") Integer pageSize){
		//获取当前登录人的信息
		String userId = CurrentUser.getCurrentUser();
		if (StringUtils.isNotBlank(userId)) {
			//根据当前登录人获取已经购买的订单
			Page<OrderVO> page = new Page<>(nowPage, pageSize);
			Page<OrderVO> result = orderServiceAPI.getOrderByUserId(Integer.valueOf(userId), page);
			Page<OrderVO> result2017 = orderServiceAPI2017.getOrderByUserId(Integer.valueOf(userId), page);
			if (null != result && result.getRecords() != null && result.getRecords().size() > 0 && null != result2017 && result2017.getRecords() != null && result2017.getRecords().size() > 0) {
				int totalPage = (int) (result.getPages() + result2017.getPages());
				//	2017和2018的订单总数合并
				List<OrderVO> orderVOList = new ArrayList<>();
				orderVOList.addAll(result.getRecords());
				orderVOList.addAll(result2017.getRecords());
				return ResponseVO.success(nowPage, totalPage, "", orderVOList);
			} else {
				return ResponseVO.serviceFail("未获取数据");
			}
		} else {
			return ResponseVO.serviceFail("用户未登陆");
		}
	}

	@RequestMapping(value = "getPayInfo", method = RequestMethod.POST)
	public ResponseVO getPay(@RequestParam(name = "orderId") String orderId){
		//获取当前登录人的信息
		String userId = CurrentUser.getCurrentUser();
		if (StringUtils.isNotBlank(userId)) {
			//根据当前登录人获取已经购买的订单
			if (null != orderId) {
				AliPayInfoVO qrCode = aliPayServiceAPI.getQRCode(orderId);
				return ResponseVO.success(IMG_PRE,qrCode);
			} else {
				return ResponseVO.serviceFail("未获取数据");
			}
		} else {
			return ResponseVO.serviceFail("用户未登陆");
		}
	}

	@RequestMapping(value = "getPayResult", method = RequestMethod.POST)
	public ResponseVO getPayResult(@RequestParam(name = "orderId") String orderId,@RequestParam(name = "tryNums") Integer tryNums){
		if(tryNums>=4){
			return ResponseVO.serviceFail("订单支付失败,请稍后重试");
		}
		//获取当前登录人的信息
		String userId = CurrentUser.getCurrentUser();
		if (StringUtils.isNotBlank(userId)) {
			//根据当前登录人获取已经购买的订单
			if (null != orderId) {
				AliPayResultVO orderStatus = aliPayServiceAPI.getOrderStatus(orderId);
				return ResponseVO.success(IMG_PRE,orderStatus);
			} else {
				return ResponseVO.serviceFail("未获取数据");
			}
		} else {
			return ResponseVO.serviceFail("用户未登陆");
		}
	}
}
